const crypto=require('crypto');
const router=require('koa-router')();
const koaBody=require('koa-body');
const events=require('events');
const config=require('../config/config');
const {User,App}=require('../models/index');
const redis=require('../models/redis.server.model');
const checkLogin=require('../middlewares/checkLogin');
const timeLimit=require('../middlewares/timeLimit');

//APP首页
router.get('/',checkLogin(),async ctx=>{
    let {loginUser}=ctx.session;
    let apps=await App.find({creator:loginUser},null,{sort:{time:-1}});

    await ctx.render('app',{
        title:'我的应用',
        loginUser:ctx.session.loginUser,
        apps,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});

//创建APP
router.get('/create',checkLogin(),async ctx=>{
    await ctx.render('createApp',{
        title:'创建APP',
        loginUser:ctx.session.loginUser,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});
router.post('/create',checkLogin(),timeLimit({action:'createApp'}),koaBody(), async ctx=>{
    let ee=new events();
    ee.on('invalid',msg=>{
        ctx.flash={error:msg};
        ctx.redirect('back');
    });

    let {name,url,desc,callback}=ctx.request.body;

    if(!name || name.length<5 || name.length>20)return ee.emit('fail','应用名长度非法(5~20)');
    if(!url)return ee.emit('fail','应用首页地址未输入');

    if(!desc || desc.length<5 || desc.length>200)return ee.emit('fail','应用描述内容长度非法(5~200)');
    if(!callback)return ee.emit('fail','应用验证回调地址未输入');

    let user=await User.findOne({_id:ctx.session.loginUser._id});
    if(!user)return ee.emit('invalid','用户不存在');

    let time=new Date();
    let client_id=crypto.createHash('md5').update([user._id,time,Math.random(),config.secret].join(':')).digest('hex');
    let secret=crypto.createHash('md5').update([name,url,desc,time,Math.random(),config.secret].join(':')).digest('hex');

    let app=new App({
        name,
        url,
        desc,
        callback,
        creator:user._id,
        client_id,
        secret,
        time
    });
    await Promise.all([
        app.save(),
        User.update({_id:user._id},{$push:{apps:app._id}}),
        redis.addLimit({action:'createApp',id:ctx.session.loginUser._id})
    ]);
    ctx.flash={success:'创建应用成功'};
    ctx.redirect('/app/settings/'+app._id);
});

//管理APP
router.get('/settings/:id',checkLogin(),timeLimit({action:'settingApp'}),koaBody(),async ctx=>{
    let {id}=ctx.params;
    let app=await App.findOne({_id:id});
    if(!app){
        ctx.flash={error:'应用不存在'};
        return ctx.redirect('back');
    }

    await ctx.render('settingsApp',{
        title:'管理APP',
        loginUser:ctx.session.loginUser,
        app,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});

module.exports=router;